package com.simple.dispatcher.servlet.utils;

import org.apache.commons.lang3.StringUtils;

public class JSONUtils {
	
	/**
	 * If the param is an empty array, then return an empty string,
	 * else return the array in JSON format
	 * @param strs
	 * @return
	 */
	public static String toStringArray(String[] strs) {
		String values = "";
		if(strs!=null && strs.length==1) {
			values = "[\"" + strs[0] + "\"]";
		} else if(strs!=null && strs.length>1) {
			values = "[\"" + strs[0] + "\"";
			for(int i=1; i<strs.length; i++) {
				values = values + ", \"" + strs[i] + "\""; 
			}
			values = values + "]";
		}
		return values;
	}
	
	public static String generateJobMetaOrFilter(String[] industries, String[] jobtitles, String[] locations, long salary, String company, String[] types, boolean isMetaData) {
		StringBuilder filter = new StringBuilder("{");
		String industryArray = toStringArray(industries);
		String jobtitleArray = toStringArray(jobtitles);
		String locationArray = toStringArray(locations);
		String typeArray = toStringArray(types);
		
		if(!StringUtils.isEmpty(industryArray)) {
			filter.append("\"industry\": " + industryArray + ", ");
		}
		if(!StringUtils.isEmpty(jobtitleArray)) {
			filter.append("\"jobtitle\": " + jobtitleArray + ", ");
		}
		if(!StringUtils.isEmpty(locationArray)) {
			filter.append("\"location\": " + locationArray + ", ");
		}
		if(salary>0) {
			if(isMetaData) {
				filter.append("\"salary\": " + salary + ", ");
			} else {
				filter.append("\"salary\": {\"value\": " + salary + ", \"op\": \"ge\"}, ");
			}
		}
		if(!StringUtils.isEmpty(company)) {
			filter.append("\"company\": \"" + company + "\", ");
		}
		if(!StringUtils.isEmpty(typeArray)) {
			filter.append("\"type\": " + typeArray + ", ");
		}
		filter.substring(0, filter.lastIndexOf(","));
		
		return filter.substring(0, filter.lastIndexOf(",")) + "}";
		//String metaData = "{\"industry\": [\"计算机\", \"互联网\"], \"jobtitle\": [\"软件研发\", \"软件测试\"], \"location\": [\"上海\", \"北京\"], \"salary\": 5000, \"company\": \"网易\", \"type\": [\"全职\", \"兼职\"]}";
		//String filter = "{\"industry\": [\"互联网\", \"计算机\"], \"jobtitle\": [\"软件研发\"], \"location\": [\"上海\", \"北京\", \"西安\"], \"salary\": {\"value\": 5000, \"op\": \"ge\"}}";
	}
	
	public static void main(String args[]) {
		String[] a = {"beijing"};
		String[] b = {"beijing", "shanghai", "ningxia"};
		String[] c = {};
		System.out.println(JSONUtils.toStringArray(a));
		System.out.println(JSONUtils.toStringArray(b));
		System.out.println(JSONUtils.toStringArray(c));
		System.out.println(JSONUtils.toStringArray(null));
		
		System.out.println(generateJobMetaOrFilter(new String[]{"计算机", "通信"}, null, null, 5000, "网易", null, true));
	}
}
